package com.qfedu.item.service.impl;

import com.google.common.base.Joiner;

import com.qfedu.item.domain.User;
import com.qfedu.item.mapper.UserMapper;


import com.qfedu.item.response.Response;
import com.qfedu.item.service.intf.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper mapper;


    @Override
    public User Login(String username, String password) {
        List<User> users = mapper.selectByName(username);
        for (User user : users) {
            if (Objects.equals(password, user.getPassword())) {
                return user;
            }
        }
        return null;
    }

    @Override
    public User likeCard(Integer userId, Integer cardId, Boolean like) {
        User user =mapper.selectByPrimaryKey(Long.valueOf(userId));
        String likeIds =user.getLiked();
        if (like){

                likeIds= StringUtils.isEmpty(likeIds)? cardId.toString():likeIds+","+cardId;

        }else{
        //collect(Collectors.toList());-Collectors类的静态方法，并返回一个Collector接口对象，该对象用于将一组数据存储到列表中。 Collectors类位于java.util.streams包下。
            List<String> likedIdList = Arrays.stream(likeIds.split(",")).collect(Collectors.toList());
            likedIdList.remove(cardId.toString());
            likeIds = Joiner.on(",").join(likedIdList);
        }
        user.setLiked(likeIds);
        mapper.updateByPrimaryKeySelective(user);

        return user;
    }


}
